<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:cart:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:cart:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:cart:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:cart:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cartList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column  label="商品图片" align="center" prop="productPic" >
        <template v-slot="scope">
          <el-image :src="src"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName"/>
      <el-table-column label="购买数量" align="center" prop="quantity" >
      <template v-slot="scope">
        <el-input-number size="mini" v-model="scope.row.quantity"
                         @change="changeNum(scope.row)" :min="1" :max="10" label="数量"/>
      </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:cart:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:cart:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align-last: right;margin: 10px">
      <div>当前已选商品总价：￥{{totalPrice}}</div>
      <el-button style="color: white; background-color: orangered" @click="settlement()"><i class="el-icon-coin"></i>结算</el-button>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品图片" prop="productPic">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview"
            :on-change="handleChange"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品id" prop="productId" >
          <el-input v-model="form.productId" placeholder="请输入商品id" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName" >
          <el-input v-model="form.productName" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="购买数量" prop="quantity" disabled>
          <el-input v-model="form.quantity" placeholder="请输入购买数量" />
        </el-form-item>
        <el-form-item label="价格" prop="price" disabled>
          <el-input v-model="form.price" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createDate">
          <el-date-picker clearable
            v-model="form.createDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 确认订单 -->
    <el-dialog :title="title" :visible.sync="openOrder" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品图片" prop="productPic">
          <el-input v-model="form.productPic" placeholder="请输入内容" disabled />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName" >
          <el-input v-model="form.productName" placeholder="请输入内容" disabled />
        </el-form-item>
        <el-form-item label="购买数量" prop="quantity" >
          <el-input v-model="form.quantity" placeholder="请输入购买数量" disabled/>
        </el-form-item>
        <el-form-item label="总金额" prop="totalPrice" >
          <el-input v-model="this.totalPrice" placeholder="请输入商品价格" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOrder">确 定</el-button>
        <el-button @click="cancelSettlement">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCart, getCart, delCart, addCart, updateCart } from "@/api/order/cart";
import {addOrders} from "@/api/order/orders";


export default {
  name: "Cart",
  data() {
    return {
      src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      file: {},
      dialogImageUrl: '',
      dialogVisible: false,
      selection:[],
      totalPrice:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 购物车表格数据
      cartList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openOrder: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //结算
    settlement(){
      console.info(this.selection)
      if (!this.selection.length){
        this.$message.error("请选择要结算的商品")
        return
      }
      this.openOrder = true
      let data = {totalAmount: this.totalPrice}

      this.form = data
      console.info(this.form)
      getCart(this.selection[0].id).then(response => {
        this.form = response.data;
        this.openOrder = true;
        this.title = "确认订单";
      });

    },
    //更新数量
    changeNum(row){
      this.form.id = row.id;
      this.form.quantity = row.quantity;
      updateCart(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
      })
      this.handleSelectionChange(this.selection);
    },
    async handleChange(file,fileList) {
      console.log(fileList[0].raw);
      console.log(file)
      this.file = file.raw;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      console.log(file.url)
      this.dialogVisible = true;
    },
    handlePreview(file) {
      console.log(file);
    },
    /** 查询购物车列表 */
    getList() {
      this.loading = true;
      listCart(this.queryParams).then(response => {
        this.cartList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelSettlement() {
      this.openOrder = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: null,
        productPic: null,
        productName: null,
        quantity: null,
        price: null,
        createDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selection = selection
      this.totalPrice = 0
      if (selection && selection.length){
        selection.forEach(item =>{
          this.totalPrice += item.quantity * item.price
        })
        this.totalPrice = this.totalPrice.toFixed(2)
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加购物车";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCart(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改购物车";
      });
    },
    //确定订单
    submitOrder() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.totalAmount = this.totalPrice;
          if (this.form.id != null) {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("下单成功");
              this.openOrder = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCart(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCart(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除购物车编号为"' + ids + '"的数据项？').then(function() {
        return delCart(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/cart/export', {
        ...this.queryParams
      }, `cart_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
